<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <!-- <crumbs @goBack="goBack" :superiorMenu="['库存管理', '库存盘点']" :currentMenu="jkeForm.title"></crumbs> -->
    <div class="form-body">
      <a-card title="基础信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="出库单编号">
            <a-input v-decorator="['entryCode']" :maxLength="21" placeholder="请输入，不输入则自动生成" />
            <!-- {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('WMS_WAREHOUSE_INVENTORY', 'inventory_code', value, queryId, callback),
                    }, -->
            <!-- <span class="btn-text code-btn" @click="genEntityCode" v-if="!isEdit">自动生成</span> -->
          </a-form-item>
          <a-form-item label="出库类型" style="margin-left: 60px" required>
            <a-select
              show-search
              v-decorator="[
                'outWarehouseType',
                {
                  rules: [
                    {
                      message: '请选择出库类型',
                    },
                  ],
                },
              ]"
              class="row-input"
              placeholder="请选择"
              allowClear
              :filter-option="filterOption"
            >
              <a-select-option :value="item.value" v-for="item in outWarehouseType" :key="item.value">
                {{ item.text }}
              </a-select-option>
            </a-select>

            <!-- validator: (rule, value, callback) => validateunitName(value, callback), -->
          </a-form-item>
          <a-form-item label="领出人" style="margin-left: 60px">
            <j-select-user-by-dep
              v-decorator="['serialSpecifications']"
              @changeRow="(a, b, c) => onChangeUser(b || {}, item.searchIndex)"
            ></j-select-user-by-dep>
          </a-form-item>
        </a-form>

        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="出库时间" required>
            <a-date-picker
              v-decorator="[
                'outWarehouseTimeText',
                {
                  rules: [
                    {
                      required: true,
                      message: '请选择出库时间',
                    },
                  ],
                },
              ]"
              mode="time"
              style="width: 100%"
              @change="operaChange"
            />
            <a-input v-decorator="['outWarehouseTime']" type="hidden" placeholder="请选择" />
          </a-form-item>

          <a-form-item style="margin-left: 60px"> </a-form-item>
          <a-form-item style="margin-left: 60px"> </a-form-item>
        </a-form>
      </a-card>
      <!-- <a-card title="自定义信息" :bordered="false" style="margin-top: 7px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="下拉选择：" required :labelCol="{ md: 8, xs: 24 }" :wrapperCol="{ md: 18, xs: 24 }">
            <a-input
              placeholder="请输入"
              :maxLength="30"
              v-decorator="[
                'unitName',
                {
                  rules: [
                    {
                      required: true,
                      message: '请选择',
                    },
                  ],
                },
              ]"
            ></a-input>
          </a-form-item>
          <a-form-item label="输入框：" :labelCol="{ md: 8, xs: 24 }" :wrapperCol="{ md: 18, xs: 20 }">
            <a-input
              placeholder="请输入"
              v-decorator="[
                'unitNotes',
                {
                  rules: [],
                },
              ]"
            ></a-input>
          </a-form-item>
          <a-form-item label="时间：" required :labelCol="{ md: 8, xs: 24 }" :wrapperCol="{ md: 18, xs: 24 }">
            <a-input
              placeholder="请输入"
              :maxLength="30"
              v-decorator="[
                'unitName',
                {
                  rules: [
                    {
                      required: true,
                      message: '请选择',
                    },
                  ],
                },
              ]"
            ></a-input>
          </a-form-item>
          <a-form-item> </a-form-item>
        </a-form>
      </a-card> -->

      <a-card title="出库物品明细" :bordered="false" style="margin-top: 12px">
        <a-col :span="24" style="margin-bottom: 38px">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="processTable.loading"
            :rowNumber="true"
            rowNumberText="序号"
            :columns="processTable.columns"
            :dataSource="processTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :actionButton="true"
            @valueChange="valueChange"
            :rowSelection="true"
            :addActionButton="false"
          >
            <span slot="options" style="padding-left: 10px">
              <a-button @click="openItProcess" type="primary" icon="plus">添加</a-button>
              <!-- <a-button @click="openItCircuit">选择生产流程</a-button> -->
            </span>
            <template v-slot:processCodeName="props">
              <a-input
                @click="openItProcess(props)"
                :value="props.value"
                placeholder="请选择"
                :read-only="true"
                :class="props.value ? 'has-value' : ''"
              >
                <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                <a-icon
                  slot="suffix"
                  type="close-circle"
                  theme="filled"
                  class="close-icon"
                  @click="getSelectValueProcess(false, '', [], props.rowId)"
                />
              </a-input>
            </template>
            <template v-slot:processWorkRate="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                @input="(e) => inputNums(props, e, 'processWorkRate', 'processTable')"
              />
            </template>
            <template v-slot:excessWorkRate="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                @input="(e) => inputNums(props, e, 'excessWorkRate', 'processTable')"
              />
            </template>
            <template v-slot:processRequire="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                :maxLength="500"
                @input="(e) => inputRequire(props, e, 'processRequire', 'processTable')"
              />
            </template>
            <template v-slot:action="props">
              <a-popconfirm
                title="是否删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(props)"
                @cancel="cancel"
              >
                <a style="padding-left: 3px; color: #f25643">删除</a>
              </a-popconfirm>
            </template>
            <span slot="options" style="padding-left: 10px">
              <a-button @click="exportAction(record)" type="primary">导入</a-button>
              <!-- <a-button @click="openItCircuit">选择生产流程</a-button> -->
            </span>
          </j-editable-table>
        </a-col>
      </a-card>
    </div>
    <div class="footer-submit form-footer">
      <a-button @click="closeBtn" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button type="primary" :loading="loadingSubmit" class="submitBtn" @click="saveForm()"> 确定 </a-button>
    </div>
    <tableSelect ref="tableSelect" @getSelectValue="getSelectValue">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline">
            <!-- <a-form-model-item label="工艺编号">
              <a-input v-model="filterFormCraft.craftCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="工艺名称">
              <a-input v-model="filterFormCraft.craftName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item> -->
            <!-- <a-button @click="searchCraft()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetCraft">重置</a-button> 
            </a-form-model-item>-->
          </a-form-model>
        </div>
      </div>
    </tableSelect>
    <tableSelect
      ref="tableSelectProcess"
      @getSelectValue="getSelectValueProcess"
      :key="indexProcess"
      @cancel="searchResetProcess"
    >
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <!-- <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
            <a-form-model-item label="工序编号">
              <a-input v-model="filterFormProcess.processCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="工序名称">
              <a-input v-model="filterFormProcess.processName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="searchProcess()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetProcess">重置</a-button>
            </a-form-model-item>
          </a-form-model> -->
        </div>
      </div>
    </tableSelect>
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import { getDictModel, productGetDictPageList } from '@/api/goodsManagement'
import { getFileListByIds } from '@/api/api'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import { apiBaseUrlDownload } from '@/utils/request'
import { APILX } from '@/api/requestLx'
import { validateDuplicateValue } from '@/utils/util'
import { fourFloatNum, accMul, accDivMin } from '@/utils/util'
import Examine from '@/components/examine'
import tableSelect from '@/components/tableSelect'

import {
  queryOptionList,
  queryCraftListByCraftId,
  teamGroup,
  deviceApi,
  inventoryApi,
  addWorkOrderApi,
  getAllCompletedContract,
} from '@/api/productOrder'
import { goodsColumns } from './column.js'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import moment from 'dayjs'

export default {
  name: 'customerForm', //新建客户
  data() {
    return {
      jkeForm: {
        title: '新建单位',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      indexProcess: 0.2,

      processDataVo: '',
      sendType: '',
      isLoading: false, //防止tab来回切换 导致数据重复渲染
      tabNor: '待盘点（0）',
      tabAbNor: '已盘点（0）',
      addOrEdit: true, //待盘点 true 已盘点false
      inventoryUserIdText: '',
      inventoryUserIdRealId: '',
      signUser: '', //盘点人 id
      warehouseIdEdit: '', //继续盘点 仓库ID
      domianURL: apiBaseUrlDownload, //表格图片展示
      getGoodsId: '', //选仓库取到的id
      //新建时候 获取明细
      inventoryTypeList: [], //盘点类型下拉
      warehouseIdList: [], //仓库数据下拉
      selectRowKeys: [],
      selectRowKeysEd: [],
      selectGoodsIds: [],
      selectGoodsIdsEd: [],
      validateDuplicateValue, //自动生成编码
      queryId: '',
      loadingSubmit: false, //防止多次提交
      submitApi: APILX.warehouseOutboundOrderInfoAdd,
      queryParam: {},
      isEdit: false,
      mainDivWidth: 0,
      attachment: '', //附件
      form: this.$form.createForm(this, { name: 'coordinated' }),
      reloadForm: false,
      unitLists: [],
      outWarehouseType: [],
      refKeys: ['processTable'],

      processTable: {
        loading: false,
        dataSource: [],
        columns: [
          ...goodsColumns,
          {
            title: '数量',
            key: 'inWarehouseNum',
            width: '20%',
            isrequired: true,
            type: FormTypes.inputNumber,
            validateRules: [],
            // slotName: 'processCodeName',
          },
        ],
      },
    }
  },
  components: {
    FileUpload,
    Examine,
    crumbs,
    tableSelect,
    JEditableTable,
  },
  created() {
    this.getdata()
    this.getUnitList()
  },
  mounted() {
    let mainDiv = document.querySelector('.ant-layout-content') //ant-layout-content
    this.mainDivWidth = `${mainDiv.clientWidth}px`
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  methods: {
    onChangeUser(v, index) {
      this.queryParam[index] = v
        .map((e) => {
          return e.id
        })
        .toString()
      this.queryParam[`${index}realname`] = v
        .map((e) => {
          return e.realname
        })
        .toString()
      this.queryParam[`${index}username`] = v
        .map((e) => {
          return e.username
        })
        .toString()
    },
    getSelectValueProcess(id, text, item, rowId) {
      item.forEach((e) => {
        this.$refs.processTable.push({
          ...e,
        })
      })
    },
    searchResetProcess() {
      // this.filterFormProcess.processCode = ''
      // this.filterFormProcess.processName = ''
      this.$refs.tableSelectProcess.searchReset()
    },
    searchProcess() {
      this.$refs.tableSelectProcess.searchQuery(this.filterFormProcess)
    },
    // 工序下拉改弹窗
    openItProcess(props) {
      // this.processRowId = props.rowId
      // const { error, values } = this.$refs.processTable.getValuesSync({ validate: true })
      // let list = values.find((i) => i.id === this.processRowId)
      // if (list.processId !== '') {
      //   this.processText = list.processName
      //   this.processValue = list.processId
      //   console.log('进 有值')
      // } else {
      //   this.processText = ''
      //   this.processValue = ''
      //   console.log('进 无值', this.processValue, this.processText)
      // }
      // this.processText = ''
      // this.processValue = ''
      let par = {
        list: '/basicserial/basicSerialInfo/list',
        visible: true, //弹窗开启
        title: '工序', //标题名称
        multi: true, //是否多选
        columns: goodsColumns, //表格配置
        value: this.goodsValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsText, //回显的中文，如：'张三'
        textKey: 'serialName', //回显的中文key,
        action: 'post',
      }
      this.$refs.tableSelectProcess.getInit(par)
    },
    minMax(value, callback) {
      console.log(value, this.form.getFieldValue('inventoryMax'))
      if (parseFloat(value) > parseFloat(this.form.getFieldValue('inventoryMax'))) {
        callback('true')
        return false
      }
      callback()
    },
    parseNumber(field) {
      let value = this.form.getFieldValue(field)
      console.log(value)

      // 解析用户输入的值
      if (value === '') {
        return 0
      }
      // 去除非数字和小数点的字符
      const newValue = value.replace(/[^\d.]/g, '')
      // 分割整数和小数部分
      const parts = newValue.split('.')
      // 获取整数和小数部分的值
      let integer = parts[0]
      let decimal = parts[1]
      // 限制整数部分最多4位
      // if (integer.length > 4) {
      //   integer = integer.slice(0, 4)
      // }
      // 限制小数部分最多4位
      if (decimal && decimal.length > 4) {
        decimal = decimal.slice(0, 4)
      }
      // 拼接整数和小数部分
      let parsedValue = integer
      if (newValue.includes('.')) {
        parsedValue += '.'
      }
      if (decimal) {
        parsedValue += decimal
      }

      let values = {}
      values[field] = parsedValue
      console.log(values)
      this.form.setFieldsValue(values)
      // 将解析后的值转为数字类型
      return ''
    },
    maxMin(value, callback) {
      if (parseFloat(value) < parseFloat(this.form.getFieldValue('inventoryMin'))) {
        callback('true')
        return false
      }
      callback()
    },
    getUnitList() {
      APILX.basicUnitList({ pageNo: 1, pageSize: 9999 }).then(({ result }) => {
        console.log(result)
        this.unitLists = result.records
      })
    },
    operaChange(a, b) {
      this.form.setFieldsValue({ outWarehouseTime: a.format('YYYY-MM-DD HH:mm:ss') })
      this.$forceUpdate()
    },
    getDic() {
      // this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-produce/produce')
      // let parameters = { dictCode: 'OUT_WAREHOUSE_TYPE' }
      APILX.warehouseOutboundOrderInfoEntryType().then((res) => {
        this.outWarehouseType = JSON.parse(JSON.stringify(res.result))
      })
      // getDictModel(parameters).then((res) => {
      //   if (res.code == 200) {
      //     this.outWarehouseType = JSON.parse(JSON.stringify(res.result))
      //   }
      //   // this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-easyMake/easyMake')
      // })
    },
    goodChange(item) {
      this.form.goodsSpec = item.spec
      this.form.goodsTypeName = item.type
      this.form.goodsTypeNameText = item.typeText
      this.form.basicUnit = item.basicUnit
      this.form.basicUnitText = item.basicUnitText
      this.form.goodsId = this.goodsValue
      this.form.goodsCodeName = `${item.goodsCode}-${item.goodsName}`
      this.$refs['ruleFormTwo'].validateField(['goodsId'])
      let craftObj = {
        pageNo: this.craft_pageNo,
        pageSize: this.craft_pageSize,
        goodsId: this.form.goodsId,
      }
      queryOptionList(craftObj).then((res) => {
        if (res.success) {
          this.craftList = res.result.records
          this.form.craftId = undefined
          if (res.result.total && res.result.total === 1) {
            // 若选中的产品关联了工艺路线，则优先默认把工艺路线的信息回填到子表
            this.form.craftId = this.craftList[0].value
            this.craftText = this.craftList[0].text
            this.craftValue = this.craftList[0].value
            this.craftChange(this.form.craftId)
          } else {
            // 若没有关联工艺路线，且物料分类只关联了一个生产流程，则默认把对应生产流程的信息回填到子表
            this.$refs.craftPath.initialize()
            this.getGoodsFlow()
          }
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
      let inventoryObj = {
        pageNo: 1,
        pageSize: 999,
        goodsId: this.form.goodsId,
      }
      this.inventoryParams.loading = true
      inventoryApi(inventoryObj).then((res) => {
        if (res.success) {
          if (res.result) {
            let newArr = res.result.records
            newArr = newArr.map((item) => {
              if (this.form.num) {
                item.planTotalNum =
                  Number(this.form.num) *
                  (Number(item.basicUseLevel) + Number(item.basicUseLevel) * Number(item.loss / 100))
                return item
              } else {
                return item
              }
            })
            console.log(newArr)
            this.inventoryParams.dataSource = newArr
          } else {
            this.inventoryParams.dataSource = []
            // this.$antdMessage.warning('该产品BOM未配置')
          }
        } else {
          this.$antdMessage.warning(res.message)
        }
        this.inventoryParams.loading = false
      })
      this.$forceUpdate()
    },
    getSelectValue(id, text, item) {
      this.form.setFieldsValue({
        processRouteId: id,
        processRouteIdText: text,
      })
    },
    // 选择合格品单位
    qualifiedChange(e, props, key) {
      let { unitList, rateQOld, inventoryGoodsQualifiedNum } = this.$refs[key].getValuesSync({
        validate: false,
        rowIds: [props.rowId],
      }).values[0]
      // console.log('inventoryGoodsQualifiedNum:',inventoryGoodsQualifiedNum,'-','rateQOld:',rateQOld);
      let old_num = inventoryGoodsQualifiedNum
        ? accMul(inventoryGoodsQualifiedNum, rateQOld)
        : '' /* 当前数值乘以单位换算比例，得到对应的基本单位数量 */
      let unit = JSON.parse(unitList).find((item) => item.id == e)
      this.$refs[key].setValues([
        {
          rowKey: props.rowId,
          values: {
            rateQ: unit.conversionRate,
            rateQOld: unit.conversionRate,
            selectUnitQ: e,
            inventoryGoodsQualifiedNum: inventoryGoodsQualifiedNum
              ? accDivMin(old_num, unit.conversionRate)
              : '' /* 基本单位数量除以辅助单位比例，得到当前数值对应辅助单位数量 */,
          },
        },
      ])
    },
    // 选择报废品单位
    scrapNumChange(e, props, key) {
      let { unitList, rateSOld, inventoryGoodsScrapNum } = this.$refs[key].getValuesSync({
        validate: false,
        rowIds: [props.rowId],
      }).values[0]
      let old_num = inventoryGoodsScrapNum ? accMul(inventoryGoodsScrapNum, rateSOld) : ''
      let unit = JSON.parse(unitList).find((item) => item.id == e)
      this.$refs[key].setValues([
        {
          rowKey: props.rowId,
          values: {
            rateS: unit.conversionRate,
            rateSOld: unit.conversionRate,
            selectUnitS: e,
            inventoryGoodsScrapNum: inventoryGoodsScrapNum ? accDivMin(old_num, unit.conversionRate) : '',
          },
        },
      ])
    },
    dataSourceItem(props, key, ediKey) {
      let item = this.$refs[ediKey].getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      let val = item[key]
      if (key == 'unitList') {
        return JSON.parse(val)
      } else {
        return val
      }
    },
    closeBtn() {
      this.jkeForm.visible = false
      // this.submitProcess()
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e && e.nodeDtos) {
        this.processDataVo = e
        // console.log(e, this.processDataVo, 'processDataVo')
        // 获取到数据后写表单提交的方法
        this.saveForm(this.sendType)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    // tab分页
    changeCurrent(key) {
      if (key == '1') {
        // this.selectRowKeys = []
        this.addOrEdit = false
        // this.getAbleTableList() //已盘点
      } else {
        // this.selectRowKeys = []
        this.addOrEdit = true // 待盘点
        // this.getEditUnAbleTable()
      }
      //   this.getData()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.getGoodsListPage.current = current
      if (this.queryId) {
        this.getEditUnAbleTable()
      } else {
        this.getGoodsList()
      }
    },
    onShowSizeChange(current, pageSize) {
      this.getGoodsListPage.pageSize = pageSize
      this.getGoodsListPage.current = current
      if (this.queryId) {
        this.getEditUnAbleTable()
      } else {
        this.getGoodsList()
      }
    },

    selectRowChange(ids) {
      this.selectRowKeys = ids
      if (this.selectRowKeys.length !== 0) {
        this.selectRowKeys.forEach((item) => {
          var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [item] }).values[0]
          if (!tableValue.inventoryGoodsQualifiedNum && !tableValue.inventoryGoodsScrapNum) {
            this.$refs.goodsTable.setValues([
              {
                rowKey: item, // 行的id
                values: {
                  // 在这里 values 中的 specifications 是你 columns 中配置的 key
                  inventoryGoodsQualifiedNum: tableValue.goodsQualifiedNum
                    ? accDivMin(tableValue.goodsQualifiedNum, tableValue.rateQ)
                    : '',
                  inventoryGoodsScrapNum: tableValue.goodsScrapNum
                    ? accDivMin(tableValue.goodsScrapNum, tableValue.rateS)
                    : '',
                  pdAmountExcludingTax: tableValue.amountExcludingTax,
                },
              },
            ])
          }
        })
      }
    },
    validateunitName(value, callback) {
      if (this.isEdit && this.queryParam.processesName == value) {
        callback()
        return false
      }
      APILX.basicProductionProcessesQueryByProcessesName({ processesName: value }).then((res) => {
        console.log(res)

        !res.result ? callback() : callback('单位值不能重复')
      })
    },

    // 工序弹窗事件-----end
    searchResetGoods() {
      this.filterForm.goodsCode = ''
      this.filterForm.goodsName = ''
      this.$refs.tableSelect.searchReset()
    },
    searchGoods() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 产品下拉改弹窗
    openIt() {
      let par = {
        list: '/basicprocess/basicProcessRouteInfo/list',
        visible: true, //弹窗开启
        title: '工艺路线', //标题名称
        multi: false, //是否多选
        columns: this.columns, //表格配置
        value: this.goodsValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsText, //回显的中文，如：'张三'
        textKey: 'processRouteName', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    // 待盘点
    getEditUnAbleTable() {
      let param = {
        id: this.queryId,
        warehouseId: this.warehouseIdEdit,
        pageNo: this.getGoodsListPage.current,
        pageSize: this.getGoodsListPage.pageSize,
      }
      this.goodsTable.dataSource = []
      this.isLoading = true
      // console.log(this.isLoading, ' getEditUnAbleTable isLoadingisLoadingisLoading')
      APILX.warehouseInventoryUnCompleteList(param).then(async (res) => {
        if (res.code == 200) {
          // console.log(res, '进来了没warehouseInventoryUnCompleteList')
          let tableData = res.result.records
          for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i]
            const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: item.goodsId })
            item.unitList = JSON.stringify(unitRes.result)
            item.rateQ = 1
            item.rateS = 1
            item.rateQOld = 1
            item.rateSOld = 1
            item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id
            item.selectUnitS = unitRes.result[unitRes.result.length - 1].id
          }
          tableData.forEach((item) => {
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.goodsTable.dataSource.push(item)
                  } else {
                    item.picUrl = require('../../../assets/img/noPicture.jpg')
                    this.goodsTable.dataSource.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../../assets/img/noPicture.jpg')
              this.goodsTable.dataSource.push(item)
            }
          })
          // this.goodsTable.dataSource = tableData
          console.log(this.goodsTable.dataSource, 'this.goodsTable.dataSource')
          this.getGoodsListPage.total = res.result.total
          setTimeout(() => {
            this.isLoading = false
          }, 1000)
        } else {
          this.$antdMessage.error(res.message)
          this.isLoading = false
        }
      })
    },
    //已盘点 table
    // 分页
    onChangePageEd(current, pageSize) {
      this.getGoodsListPageEd.current = current
      this.getAbleTableList()
    },
    onShowSizeChangeEd(current, pageSize) {
      this.getGoodsListPageEd.pageSize = pageSize
      this.getGoodsListPageEd.current = current
      this.getAbleTableList()
    },

    selectRowChangeEd(ids) {
      this.selectRowKeysEd = ids
      console.log(this.selectRowKeysEd, 'selectRowChangeEd')
      if (this.selectRowKeysEd.length !== 0) {
        this.selectRowKeysEd.forEach((item) => {
          var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [item] }).values[0]
          this.selectGoodsIdsEd.push(tableValue.goodsId)
          if (!tableValue.inventoryGoodsQualifiedNum && !tableValue.inventoryGoodsScrapNum) {
            this.$refs.goodsTableEd.setValues([
              {
                rowKey: item, // 行的id
                values: {
                  // 在这里 values 中的 specifications 是你 columns 中配置的 key
                  // inventoryGoodsQualifiedNum: tableValue.goodsQualifiedNum || '',
                  // inventoryGoodsScrapNum: tableValue.goodsScrapNum || '',
                  inventoryGoodsQualifiedNum: tableValue.goodsQualifiedNum
                    ? accDivMin(tableValue.goodsQualifiedNum, tableValue.rateQ)
                    : '',
                  inventoryGoodsScrapNum: tableValue.goodsScrapNum
                    ? accDivMin(tableValue.goodsScrapNum, tableValue.rateS)
                    : '',
                },
              },
            ])
          }
        })
      }
    },
    // 已盘点 编辑
    getAbleTableList() {
      console.log('selectRowKeysEd', this.selectGoodsIdsEd)
      let param = {
        id: this.queryId,
        pageNo: this.getGoodsListPageEd.current,
        pageSize: this.getGoodsListPageEd.pageSize,
      }
      this.goodsTableEd.dataSource = []
      this.isLoading = true
      // console.log(this.isLoading, ' getAbleTableList isLoadingisLoadingisLoading')
      APILX.wmsWarehouseInventoryCompleteList(param).then(async (res) => {
        if (res.code == 200) {
          // console.log(res, '进来了没warehouseInventoryUnCompleteList')
          let tableData = res.result.records
          for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i]
            const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: item.goodsId })
            item.unitList = JSON.stringify(unitRes.result)
            if (item.goodsQualifiedUnitId) {
              let unitQ = unitRes.result.find((u) => u.id == item.goodsQualifiedUnitId)
              let unitS = unitRes.result.find((u) => u.id == item.goodsScrapUnitId)
              item.selectUnitQ = unitQ ? unitQ.id : unitRes.result[unitRes.result.length - 1].id
              item.selectUnitS = unitS ? unitS.id : unitRes.result[unitRes.result.length - 1].id

              item.rateQ = unitQ ? unitQ.conversionRate : 1
              item.rateQOld = unitQ ? unitQ.conversionRate : 1

              item.rateS = unitS ? unitS.conversionRate : 1
              item.rateSOld = unitS ? unitS.conversionRate : 1

              item.inventoryGoodsQualifiedNum = accDivMin(item.inventoryGoodsQualifiedNum, item.rateQ)
              item.inventoryGoodsScrapNum = accDivMin(item.inventoryGoodsScrapNum, item.rateS)
            } else {
              item.rateQ = 1
              item.rateS = 1
              item.rateQOld = 1
              item.rateSOld = 1
              item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id
              item.selectUnitS = unitRes.result[unitRes.result.length - 1].id
            }
          }
          tableData.forEach((item) => {
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.goodsTableEd.dataSource.push(item)
                  } else {
                    item.picUrl = require('../../../assets/img/noPicture.jpg')
                    this.goodsTableEd.dataSource.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../../assets/img/noPicture.jpg')
              this.goodsTableEd.dataSource.push(item)
            }
            if (item.inventoryGoodsQualifiedNum == '-') {
              item.inventoryGoodsQualifiedNum = 0.0
            }
            if (item.inventoryGoodsScrapNum == '-') {
              item.inventoryGoodsScrapNum = 0.0
            }
          })
          this.getGoodsListPageEd.total = res.result.total
          let _that = this
          setTimeout(() => {
            _that.isLoading = false
            console.log(_that.selectGoodsIdsEd, 'this.goodsTableEd.dataSource')
            const { error, values } = _that.$refs.goodsTableEd.getValuesSync({ validate: false })
            let ids = []
            let goods = values.filter((item) => _that.selectGoodsIdsEd.includes(item.goodsId))
            // console.log('aaaaaa',aaa);
            for (let g = 0; g < goods.length; g++) {
              ids.push(goods[g].id)
            }
            _that.$refs.goodsTableEd.setSelection(ids)
          }, 1000)
          // this.isLoading = false
        } else {
          this.$antdMessage.error(res.message)
          this.isLoading = false
        }
      })
    },

    /* 获取编辑详情 */
    initForm(v, copy = false) {
      this.jkeForm.visible = true
      // this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-easyMake/easyMake')
      if (v) {
        this.queryParam = v

        if (copy) {
          this.isEdit = false
          this.submitApi = APILX.warehouseOutboundOrderInfoAdd
          this.queryId = null
        } else {
          this.submitApi = APILX.warehouseOutboundOrderInfoEdit
          this.isEdit = true
          this.queryId = v.id
        }
        // console.log(id, '00.0.0.0')

        let _this = this
        setTimeout(() => {
          _this.form.setFieldsValue(v)
        }, 100)
      } else {
        this.jkeForm.title = '新建物品'
        this.isEdit = false
        this.submitApi = APILX.warehouseOutboundOrderInfoAdd
        this.queryId = null
      }
      this.getDic()
    },

    // 提交
    saveForm(all) {
      this.handleSubmit([], all)
    },
    // 提交
    saveFormEd(newparam1, all) {
      // console.log(all, 'all')
      if (this.selectRowKeysEd.length !== 0) {
        const { error, values } = this.$refs.goodsTableEd.getValuesSync({ validate: true })
        let newparamEd = values.filter((item) => this.selectRowKeysEd.includes(item.id))
        //合并两个数组
        let newparam = newparam1.concat(newparamEd)
        // console.log(newparam, 'newparam')
        this.handleSubmit(newparam, all)
      } else {
      }
      this.handleSubmit(newparam1, all)

      // console.log(all, 'all2')
    },
    handleSubmit(tableValue, all) {
      this.form.validateFields((err, values) => {
        console.log(values, 'values form')
        if (!err) {
          this.submitTo(tableValue, values, all)
        }
      })
    },
    submitTo(tableValue, values, all) {
      // console.log(all, 'all 进入最终submit')
      // console.log(tableValue, 'tableValue')
      const { error, values: tableValues } = this.$refs.processTable.getValuesSync({ validate: true })
      // let newparamEd = values.filter((item) => this.selectRowKeysEd.includes(item.id))
      console.log(tableValues)
      let parameters = {
        ...values,
        entryDetails: tableValues.map((item) => {
          return {
            entryId: '',
            serialId: item.id,
            inWarehouseNum: item.inWarehouseNum,
          }
        }),
        id: this.queryId || undefined,
      }

      this.loadingSubmit = true
      this.submitApi(parameters).then((res) => {
        if (res.code == 200) {
          this.loadingSubmit = false
          let subMsg = this.isEdit ? '物品编辑成功！' : '物品添加成功！'
          this.$antdMessage.success(subMsg)
          this.goBack()
        } else {
          this.loadingSubmit = false
          this.$antdMessage.error(res.message)
        }
      })
    },
    submitAll(tableValue, values, all) {
      // tableValue.forEach((item) => {
      //   if (item.inventoryGoodsQualifiedNum == '') {
      //     item.inventoryGoodsQualifiedNum = 0
      //   }
      //   if (item.inventoryGoodsScrapNum == '') {
      //     item.inventoryGoodsScrapNum = 0
      //   }
      //   item.inventoryGoodsQualifiedNum = accMul(item.inventoryGoodsQualifiedNum, item.rateQ)
      //   item.inventoryGoodsScrapNum = accMul(item.inventoryGoodsScrapNum, item.rateS)
      // })
      let that = this
      that.$antdConfirm({
        title: '确定盘点完毕吗?',
        content: `盘点完毕后，无法更改盘点数据`,
        onOk() {
          // console.log(all, 'all 弹窗')
          that.submitTo(tableValue, values, all)
        },
        onCancel() {},
      })
    },
    //下拉选择数据接口
    getdata() {
      // APILX.wmsWarehouseQueryList().then((res) => {
      //   if (res.code == 200) {
      //     this.warehouseIdList = res.result
      //   } else {
      //     that.$antdMessage.error(res.message)
      //   }
      // })
      //   取盘点类型
      // let parametersType = { dictCode: 'inventory_type' }
      // getDictModel(parametersType).then((res) => {
      //   // console.log(res, 'resType')
      //   if (res.code == 200) {
      //     this.inventoryTypeList = res.result
      //   } else {
      //     that.$antdMessage.error(res.message)
      //   }
      // })
    },
    setColor(props) {
      // if (props.text == 0) {
      //   return '#0f0!important'
      // }
      var newNum = props.text
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log(tableValue, 'tableValuetableValuetableValue')
      if (Number(newNum) > tableValue.goodsQualifiedNum) {
        return '#ff4d4f'
      } else {
        return '#00b042'
      }
    },
    setColor2(props) {
      var newNum = props.text
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (Number(newNum) > tableValue.goodsScrapNum) {
        return '#ff4d4f'
      } else {
        return '#00b042'
      }
    },

    inputNum(e, props, inputKey) {
      let newNum = fourFloatNum(e.target.value)
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (inputKey == 'inventoryGoodsQualifiedNum') {
        if (Number(newNum) > tableValue.goodsQualifiedNum) {
          // this.$antdMessage.warning('库存不足：本次盘点合格品不得大于账面合格品')
        } else {
        }
      }
      if (inputKey == 'inventoryGoodsScrapNum') {
        if (Number(newNum) > tableValue.goodsScrapNum) {
          // this.$antdMessage.warning('库存不足：本次盘点报废品不得大于账面报废品')
        } else {
        }
      }
      this.$refs.goodsTable.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            [inputKey]: newNum,
          },
        },
      ])
      // var tableValue2 = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log(tableValue2, 'tableValue2tableValue2')
    },
    pdMoney(val, props, tableType) {
      this.$refs[tableType].setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            pdAmountExcludingTax: val,
          },
        },
      ])
    },
    inputFocus(props) {
      // console.log(props, 'props')
      const isSelect = this.selectRowKeys.filter((each) => each == props.rowId)
      if (isSelect.length == 0) {
        // this.selectRowKeys.push(props.rowId)
        this.$antdMessage.error('请先勾选当前数据')
        // console.log(this.selectRowKeys, 'this.selectRowKeys')
      }
    },

    // 已盘点
    inputFocusEd(props) {
      // console.log(props, 'props')
      const isSelect = this.selectRowKeysEd.filter((each) => each == props.rowId)
      if (isSelect.length == 0) {
        // this.selectRowKeysEd.push(props.rowId)
        this.$antdMessage.error('请先勾选当前数据')
        // console.log(this.selectRowKeysEd, 'this.selectRowKeysEd')
      }
    },
    setColorEd(props) {
      // console.log(props.text)
      // if (props.text == 0) {
      //   return '#0f0!important'
      // }
      var newNum = props.text
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log(tableValue, 'tableValuetableValuetableValue')
      if (Number(newNum) > tableValue.goodsQualifiedNum) {
        return '#ff4d4f'
      } else {
        return '#00b042'
      }
    },
    setColor2Ed(props) {
      var newNum = props.text
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (Number(newNum) > tableValue.goodsScrapNum) {
        return '#ff4d4f'
      } else {
        return '#00b042'
      }
    },

    inputNumEd(e, props, inputKey) {
      let newNum = fourFloatNum(e.target.value)
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (inputKey == 'inventoryGoodsQualifiedNum') {
        if (Number(newNum) > tableValue.goodsQualifiedNum) {
          // this.$antdMessage.warning('库存不足：本次盘点合格品不得大于账面合格品')
        } else {
        }
      }
      if (inputKey == 'inventoryGoodsScrapNum') {
        if (Number(newNum) > tableValue.goodsScrapNum) {
          // this.$antdMessage.warning('库存不足：本次盘点报废品不得大于账面报废品')
        } else {
        }
      }
      this.$refs.goodsTableEd.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            [inputKey]: newNum,
          },
        },
      ])
      // var tableValue2 = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log(tableValue2, 'tableValue2tableValue2')
    },

    // 已盘点结束

    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'WMS_WAREHOUSE_INVENTORY' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            inventoryCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    valueChange(type, row) {
      // console.log(type, row, 'value change type')
    },
    //   选仓库带明细
    selectOrder(v) {
      if (v) {
        this.getGoodsId = v
        this.getGoodsList()
      }
    },
    getGoodsList() {
      let param = {
        id: this.getGoodsId,
        pageNo: this.getGoodsListPage.current,
        pageSize: this.getGoodsListPage.pageSize,
      }
      this.goodsTable.dataSource = []
      this.isLoading = true
      APILX.getGoodsListByWarehouseId(param).then(async (res) => {
        if (res.result) {
          let tableData = res.result.records
          for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i]
            const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: item.goodsId })
            item.unitList = JSON.stringify(unitRes.result)
            item.rateQ = 1
            item.rateS = 1
            item.rateQOld = 1
            item.rateSOld = 1
            item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id
            item.selectUnitS = unitRes.result[unitRes.result.length - 1].id
          }
          tableData.forEach((item) => {
            // const unitRes = await API.findUnitListByGoodsIdSync({goodsId: item.goodsId})
            // item.unitList = JSON.stringify(unitRes.result)
            // item.rateQ = 1
            // item.rateS = 1
            // item.selectUnitQ = unitRes.result[unitRes.result.length-1].id
            // item.selectUnitS = unitRes.result[unitRes.result.length-1].id
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.goodsTable.dataSource.push(item)
                  } else {
                    item.picUrl = require('../../../assets/img/noPicture.jpg')
                    this.goodsTable.dataSource.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../../assets/img/noPicture.jpg')
              this.goodsTable.dataSource.push(item)
            }
          })
          // console.log(this.goodsTable.dataSource, 'this.goodsTable.dataSource')
          this.getGoodsListPage.total = res.result.total
          this.tabNor = `待盘点（${this.getGoodsListPage.total}）`
          this.isLoading = false
        }
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.$emit('refresh')
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      // console.log('上传的附件id：', v)
    },
    /* 选盘点人 */
    userFilter(v, row) {
      // console.log(v, row)
      this.form.setFieldsValue({
        inventoryUserId: v,
      })
      if (row.length > 0) {
        this.signUser = row[0].id
      } else {
        this.signUser = ''
      }
    },
    // 下拉搜索
    filterOption(input, option) {
      // console.log('inputoption', input, option)
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    cancel() {},
    setGoodsScrapNum(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsScrapNum) {
        return tableValue.goodsScrapNum
      } else {
        return ''
      }
    },
    setUnit(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.assistUnit) {
        return tableValue.assistUnit
      } else {
        return ''
      }
    },
    setSpec(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.spec) {
        return tableValue.spec
      } else {
        return '-'
      }
    },
    setName(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsName) {
        return tableValue.goodsName
      } else {
        return ''
      }
    },
    setCode(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsCode) {
        return tableValue.goodsCode
      } else {
        return ''
      }
    },

    // 已盘点
    setGoodsScrapNumEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsScrapNum) {
        return tableValue.goodsScrapNum
      } else {
        return ''
      }
    },
    // 辅助单位账面库存数量
    setNumAssistUnit(props, key, numTextKey) {
      var tableValue = this.$refs[key].getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log('setNumAssistUnit', tableValue)
      // return tableValue.goodsScrapNumTextAssistUnit || '-'
      return tableValue[numTextKey] || '-'
    },
    setUnitEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.assistUnit) {
        return tableValue.assistUnit
      } else {
        return ''
      }
    },
    setSpecEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.spec) {
        return tableValue.spec
      } else {
        return ''
      }
    },
    setNameEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsName) {
        return tableValue.goodsName
      } else {
        return ''
      }
    },
    setCodeEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsCode) {
        return tableValue.goodsCode
      } else {
        return ''
      }
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 180px);
  overflow-y: scroll;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
.pic-f {
  box-sizing: border-box;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 20px 10px;
  .pic-r {
    flex: 1;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #444444;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    .subDiv {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.imgClass {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}
.my-input {
  padding: 4px 30px 4px 11px;
  border-radius: 3px;
  border: solid 1px #cdcdcd;
}
input::-webkit-input-placeholder {
  color: #cdcdcd;
}
input::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #cdcdcd;
}
input:-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: #cdcdcd;
}
input:-ms-input-placeholder {
  /* Internet Explorer 10-11 */
  color: #cdcdcd;
}
</style>
